<?php require_once(BASEPATH.'application/controllers/validaciones.php');
/*
 * Facturacion
 * @author  : Katy Oviedo
 * Version  :2.0
 * Date     :23/02/2012 
 */
class sfacdespfyco extends validaciones{

	function sfacdespfyco()	{
		parent::Controller(); 
		$this->load->library("rapyd");
        $this->load->library('Inventario');
	}
	function index(){
		redirect("ventas/sfacdespfyco/filteredgrid");
	}
	
    //buscar facturas a despachar
    
    function filteredgrid(){
		
		//$this->db->query("UPDATE remision as a SET fnumero=(SELECT fnumero FROM spre as b where a.factura=b.numero AND facturado='S')");
		//$this->db->query("UPDATE remision as a SET almacen=(SELECT almacen FROM sfac as b where tipo_doc='FC' AND a.fnumero=b.numero)");
		//$this->db->query("UPDATE despachos  as a set a.factura=(SELECT fnumero FROM spre as b where a.presup=b.numero)"); 
        
		$this->rapyd->load('datagrid2','datafilter');
		$this->rapyd->uri->keep_persistence();

		$atts = array(
			'width'      => '800',
			'height'     => '600',
			'scrollbars' => 'yes',
			'status'     => 'yes',
			'resizable'  => 'yes',
			'screenx'    => '0',
			'screeny'    => '0'
		);

		$scli=array(
		'tabla'   =>'scli',
		'columnas'=>array(
		'cliente' =>'C&oacute;digo Cliente',
		'nombre'=>'Nombre',
		'contacto'=>'Contacto'),
		'filtro'  =>array('cliente'=>'C&oacute;digo Cliente','nombre'=>'Nombre'),
		'retornar'=>array('cliente'=>'cod_cli'),
		'titulo'  =>'Buscar Cliente');
		$boton=$this->datasis->modbus($scli);
        
        $revisa = anchor('ventas/sfacdespfyco/revision',' Revisar Procesos');
        
        $filter = new DataFilter("B&uacute;squeda de Gu&iacute;as de Despacho / $revisa");
        $select=array( "a.facturado","a.almacen","a.tipo_doc","a.fnumero","a.moneda","if(a.factura IS NULL ,'00000000000',a.factura ) numero","b.id id_spre","a.id", "a.factura","a.motivo","a.fecha", "a.usuario", 
        "a.estampa", "a.nguia", "a.ftraslado", "a.destinatario","a.rucd","a.flete");
		$filter->db->select($select);
		$filter->db->from('remision AS a');
        $filter->db->join('spre AS b','a.factura=b.numero','LEFT');
        //$filter->db->where('b.tipo_doc','FC');
        $filter->db->orderby('a.nguia','DESC');
        
		//$filter->db->where('facturado','S');
		
        $ano=date("Y");
        $mes=date("m");
        
        $filter->fechad = new dateonlyField('Desde', 'fechad','d/m/Y');
		$filter->fechah = new dateonlyField('Hasta', 'fechah','d/m/Y');
		$filter->fechad->clause  =$filter->fechah->clause ='where';
		$filter->fechad->db_name =$filter->fechah->db_name='a.fecha';
		//$filter->fechad->insertValue = date("Y-m-d", mktime(0, 0, 0,$mes, 1, $ano));
		$filter->fechad->insertValue = date("Y-m-d", mktime(0, 0, 0, 01, 1, $ano));
		$filter->fechah->insertValue = date('Y-m-d');
		$filter->fechah->size=$filter->fechad->size=10;
		$filter->fechad->operator='>=';
		$filter->fechah->operator='<=';

		$filter->nguia = new inputField('N&uacute;mero de Gu&iacute;a', 'a.nguia');
		$filter->nguia->size = 20;
        
        $filter->factura = new inputField('Presupuesto', 'a.factura');
		$filter->factura->size = 20;

		$filter->cliente = new inputField('Nombre de Cliente', 'destinatario');
		$filter->cliente->size = 20;
		$filter->cliente->append($boton);
		
		$filter->tipo_doc = new  dropdownField ('Tipo','a.tipo_doc');
		$filter->tipo_doc->option("",'Todos');
		$filter->tipo_doc->option("FC",'Guia Emitida');
        $filter->tipo_doc->option("X",'Guia Eliminada');
        $filter->tipo_doc->style ="width:200px";
        
        $filter->facturado = new  dropdownField ('Gu&iacute;as facturadas','a.facturado');
		$filter->facturado->option("",'Todos');
		$filter->facturado->option("S",'Si estan facturadas');
		$filter->facturado->option("N",'No estan facturadas');
		$filter->facturado->style ="width:200px";
		
		$filter->buttons('reset','search');
		$filter->build("dataformfiltro");
        
        function boton($tipo=''){
			
			IF($tipo=='X'){
				return 2;
			}else{
				return 1;	
			}
		}
		
		$grid = new DataGrid2("");
		$grid->order_by('nguia','desc');
		$grid->per_page = 10;
		$grid->use_function('boton');
		
		$uri = anchor('ventas/sfacdespfyco/detalle/<#numero#>/<#id_spre#>/','<#nguia#>');
		
		$uri_2  = anchor_popup('formatos/ver/GUIA/<#id#>',img(array('src'=>'images/pdf_logo.gif','border'=>'0','alt'=>'Ver Html','height'=>'15','title'=>'Ver Html')),$atts);
		$uri_2 .= anchor_popup("formatos/verhtml/GUIA/<#id#>",img(array('src'=>'images/html_icon.gif','border'=>'0','alt'=>'Ver Pdf','height'=>'15','title'=>'Ver Pdf')),$atts);
		$uri_2 .= img(array('src'=>'images/<boton><#tipo_doc#></boton>.gif','border'=>'0','alt'=>'Estado','height'=>'12','title'=>'Estado'));
		
		$grid->column(' ',$uri_2,"align='center'");
		$grid->column_orderby('Guia'          ,$uri                                               ,'numero'      );
		$grid->column_orderby('Presupuesto'   ,'<#numero#>'                                       ,'factura'     );
		$grid->column_orderby('Factura'       ,'<#fnumero#>'                                      ,'fnumero'     );
		$grid->column_orderby('Almacen'       ,'<#almacen#>'                                      ,'almacen'     );
        $grid->column_orderby('Nombre'        ,'destinatario'                                     ,'destinatario');
        $grid->column_orderby('Emision'       ,'<dbdate_to_human><#fecha#></dbdate_to_human>'     ,'fecha'       );
        $grid->column_orderby('Traslado'      ,'<dbdate_to_human><#ftraslado#></dbdate_to_human>' ,'ftraslado'   );    
			
		$grid->add("ventas/transportistas/filteredgrid",'Empresas de Transporte');		
		
		$grid->totalizar('flete');
        
        $grid->output;
		$grid->build('datagridST');
		//echo $grid->db->last_query();
		
		
		$style ='
		<style type="text/css">
		.fakeContainer { /* The parent container */
		    margin: 5px;
		    padding: 0px;
		    border: none;
		    width: 1200px; /* Required to set */
		    height: 350px; /* Required to set */
		    overflow: hidden; /* Required to set */
		}
		</style>	
		';
			
		$data['style']  = style("redmond/jquery-ui.css");
		$data["script"]  = script("jquery.js");
		$data["script"] .= script('superTables.js');
		$data['style']   = $style;
		$data['style']  .= style('superTables.css');

		$data['filtro']  = $filter->output;
		$data['content'] = $grid->output;
		
		$data['head']    = $this->rapyd->get_head();
		$data['title']   = heading('Gu&iacute;as de Despacho');
		$this->load->view('view_ventanas', $data);
	}
    function revision(){
        
    $mSQL=$this->db->query("SELECT a.codigo,a.nguia,
    (SELECT j.factura FROM costos as j WHERE a.codigo=j.codigo and j.factura=a.nguia AND j.origen='3I')costo 
    FROM despachos as a 
    where  a.tipo_doc='FC' and a.codigo<>'CORTINA'
    HAVING costo is null
    ORDER BY a.nguia DESC");
    
    $cost=$this->datasis->dameval("SELECT COUNT(*) FROM costos WHERE origen='3I'");
    $desp=$this->datasis->dameval("SELECT COUNT(*) FROM despachos WHERE tipo_doc='FC' AND codigo<>'CORTINA' and remision<>0");
     
    echo '<h5>TOTAL DE PRODUCTOS DESPACHADOS EN GUIAS:'.$desp.'</h5></br>';
    echo '<h5>TOTAL DE PRODUCTOS CARGADOS EN KARDEX:'.$cost.'</h5></br>';
    
    foreach($mSQL->result() as $items ){
        
        echo 'CODIGO: '.$items->codigo.' NUMERO DE GUIA: '.$items->nguia.'</br>';
    }
    
    }
    function dataedit($estado='',$nguia='', $factura=''){
		
        $this->rapyd->load("dataedit");				
		$tipo=$this->datasis->traevalor('TIPO');
        
        $link2=site_url('ventas/common/get_zona');
        $link3=site_url('ventas/common/get_estados');
        $link4=site_url('ventas/common/get_municipios');
        $link5=site_url('ventas/common/get_zona2');
        $link6=site_url('ventas/common/get_estados2');
        $link7=site_url('ventas/common/get_municipios2');
        
        $script='
		$(document).ready(function(){
			$("#pais").change(function(){
				$.post("'.$link2.'",{ pais:$(this).val() },function(data){$("#zona").html(data);})
			});
			$("#zona").change(function(){
				$.post("'.$link3.'",{ zona:$(this).val() },function(data){$("#estado").html(data);})
			});
			$("#estado").change(function(){
				$.post("'.$link4.'",{ estado:$(this).val(),zona:$(zona).val() },function(data){$("#municipio").html(data);})
			});
            $("#pais2").change(function(){
				$.post("'.$link5.'",{ pais2:$(this).val() },function(data){$("#zona2").html(data);})
			});
			$("#zona2").change(function(){
				$.post("'.$link6.'",{ zona2:$(this).val() },function(data){$("#estado2").html(data);})
			});
			$("#estado2").change(function(){
				$.post("'.$link7.'",{ estado2:$(this).val(),zona2:$(zona2).val() },function(data){$("#municipio2").html(data);})
			});
		});
		</script>
		';
		
		$modbus_trans=array(
			'tabla'   =>'transportistas',
			'columnas'=>array(
                'nombre'=>'Nombre',
                'direccion'=>'Direccion'),
			'filtro'  =>array('nombre'=>'Nombre'),
			'retornar'=>array(
                'nombre'=>'transportista',
                'direccion'=>'direc'),
                'p_uri'   => array(4=>'<#i#>'),
			'titulo'  =>'Buscar Empresa de Trasnporte');

		$boton=$this->datasis->p_modbus($modbus_trans);

        $edit = new DataEdit(" ", "remision");
        $edit->back_url = site_url("ventas/sfacdespfyco/");

         if($edit->_status=='show'){
			 
            $factura=$edit->_dataobject->get("factura");
            $nguia=$edit->_dataobject->get("nguia");
            $id=$edit->_dataobject->get("id");
            $id_spre = $this->datasis->dameval("SELECT id FROM spre WHERE numero='$factura'");
            $edit->back_url = site_url("ventas/sfacdespfyco/detalle/$factura/$id_spre");
            //$this->inventario->sp_costos($id,'3I');
              
        } 
        
        $cliente=$this->datasis->dameval("SELECT nombre FROM spre WHERE numero='$factura'");
        $rifci=$this->datasis->dameval("SELECT rifci FROM spre WHERE numero='$factura'");
        $transportista=$this->datasis->dameval("SELECT transportista FROM spre WHERE numero='$factura'");
        $direc=$this->datasis->dameval("SELECT direct FROM spre WHERE numero='$factura'");
        $atencion=$this->datasis->dameval("SELECT atencion FROM spre WHERE numero='$factura'");
        $tipod=$this->datasis->dameval("SELECT tipod FROM spre WHERE numero='$factura'");
        $observa=$this->datasis->dameval("SELECT observa FROM spre WHERE numero='$factura'");
        
        
        $edit->script($script,"create");
		$edit->script($script,"modify");
		    				
        $edit->pre_process('update','_pre_update');
        //$edit->pre_process('delete','_pre_delete');
        $edit->post_process('update','_post_update');
		$edit->post_process('insert','_post_insert');
		$edit->pre_process('insert','_pre_insert');
                
        $edit->id = new hiddenField(" ", 'id');
        $edit->usuario  = new autoUpdateField('usuario', $this->session->userdata('usuario'), $this->session->userdata('usuario'));
           
        $edit->tipo_doc = new  dropdownField ('Tipo','tipo_doc');
		$edit->tipo_doc->option("FC",'Guia Emitida');
        $edit->tipo_doc->option("X",'Guia Eliminada');
        $edit->tipo_doc->mode = 'autohide';
        //$edit->tipo_doc->when=array('show');
        $edit->tipo_doc->style='width:200px;';
        $edit->tipo_doc->group="Informaci&oacute;n del Movimiento";
        
        $edit->almacen = new  dropdownField ('Almac&eacute;n', 'almacen');
	    $edit->almacen->options("SELECT ubica, CONCAT(ubica,' ',ubides) nombre FROM caub WHERE gasto='N' and activo='S' ORDER BY ubica");
		$edit->almacen->option("X",'Guia Eliminada');
		$edit->almacen->rule = 'required';
		$edit->almacen->mode = 'autohide';
		$edit->almacen->style='width:200px;';
		$edit->almacen->group="Informaci&oacute;n del Movimiento";
		        
        $edit->moneda = new dropdownField("Moneda", "moneda");
		$edit->moneda->style='width:200px;';
		$edit->moneda->option("","Seleccione la moneda" );
		$edit->moneda->options("SELECT codigo,descrip FROM moneda ORDER BY codigo");
		$edit->moneda->rule = 'required';
		$edit->moneda->group="Informaci&oacute;n del Movimiento";
		
		$edit->cambio = new inputField('Cambio', 'cambio');
		$edit->cambio->css_class ='inputnum';
		$edit->cambio->size      = 12;
		$edit->cambio->when=array('show');
		$edit->cambio->group="Informaci&oacute;n del Movimiento";
		
        $edit->nguia = new inputField('N&deg; de Guia ','nguia');
		$edit->nguia->size = 15;
        //$edit->nguia->when = array("show","modify");
        $edit->nguia->insertValue =$nguia;
        $edit->nguia->mode = 'autohide';
        //$edit->nguia->readonly  = true;
        $edit->nguia->rule= "callback_chexiste";
        $edit->nguia->group="Informaci&oacute;n del Movimiento";
        
        $edit->factura = new inputField('Presupuesto', 'factura');
		$edit->factura->size = 40;
        $edit->factura->when = array("show");
        $edit->factura->insertValue =$factura;
        $edit->factura->group="Informaci&oacute;n del Movimiento";
                 
		$edit->fecha = new DateonlyField('Fecha', 'fecha','Y-m-d');
		$edit->fecha->insertValue = date('Y-m-d');
		$edit->fecha->rule = 'required';
		//$edit->fecha->mode = 'autohide';
		$edit->fecha->size = 12;
		$edit->fecha->rule= "callback_cambio";
		$edit->fecha->group="Informaci&oacute;n del Movimiento";
        
        $edit->ftraslado = new DateonlyField('Fecha de Traslado', 'ftraslado','Y-m-d');
        $edit->ftraslado->insertValue = date('Y-m-d');
		$edit->ftraslado->rule = 'required';
		$edit->ftraslado->size = 12;
		$edit->ftraslado->group="Informaci&oacute;n del Movimiento";
		                      				
        $edit->domiciliop = new textareaField("Direcci&oacute;n","domiciliop");
		$edit->domiciliop->rule = "required|strtoupper";
		$edit->domiciliop->cols = 60;
		$edit->domiciliop->rows =2;
		$edit->domiciliop->group="Domicilio de Partida";
        
        $edit->pais = new dropdownField("Pais","pais");
        $edit->pais->db_name='regionp';
		$edit->pais->style = "width:270px";
		//$edit->pais->rule = "required";
		$edit->pais->option("","Seleccionar");
		$edit->pais->options("SELECT codigo, nombre FROM pais ORDER BY nombre");
		$edit->pais->group = "Domicilio de Partida";
		
		$edit->zona = new dropdownField("Departamento", "zona");
        $edit->zona->db_name='departap';
		$edit->zona->style = "width:270px";
		//$edit->zona->rule = "required";
		$edit->zona->group = "Domicilio de Partida";
		if($edit->_status=='show'||$edit->_status=='modify'){ 
			$pais =$edit->_dataobject->get("regionp");
			$edit->zona->options("SELECT codigo, nombre FROM zona WHERE pais='$pais' ORDER BY nombre");
		}else{
			$edit->zona->option("","Seleccione una Regi&oacute;n");
		}	
    
		$edit->estado = new dropdownField("Provincia","estado");
		//$edit->estado->option("","Seleccione una Zona");
        $edit->estado->db_name='provinciap';
		$edit->estado->style = "width:270px";
		//$edit->estado->rule = "required";
		$edit->estado->group = "Domicilio de Partida";
		if($edit->_status=='show'||$edit->_status=='modify'){ 
			$zona =$edit->_dataobject->get("departap");
			$edit->estado->options("SELECT codigo, nombre FROM estado WHERE zona='$zona' ORDER BY nombre");
		}else{
			$edit->estado->option("","Seleccione un Departamento");
		}	
				
		$edit->municipios = new dropdownField("Distrito","municipio");
		//$edit->municipios->option("","Seleccione un Municipio");
        $edit->municipios->db_name='distritop';
		$edit->municipios->style = "width:270px";
		//$edit->municipios->rule = "required";
		$edit->municipios->group = "Domicilio de Partida";
		if($edit->_status=='show'||$edit->_status=='modify'){ 
			$estado   =$edit->_dataobject->get("provinciap");
			$zona     =$edit->_dataobject->get("departap");
			$edit->municipios->options("SELECT codigo, nombre FROM municipio WHERE estado='$estado' and zona='$zona' ORDER BY nombre");
		}else{
			$edit->municipios->option("","Seleccione una Provincia");
		}
        
        $edit->domiciliol = new textareaField("Direcci&oacute;n","domiciliol");
		$edit->domiciliol->rule = "required|strtoupper";
		$edit->domiciliol->cols = 60;
		$edit->domiciliol->rows =2;
		$edit->domiciliol->group="Domicilio de Llegada";
        
        $edit->pais2 = new dropdownField("Pais","pais2");
        $edit->pais2->db_name='regionl';
		$edit->pais2->style = "width:270px";
		//$edit->pais2->rule = "required";
		$edit->pais2->option("","Seleccionar");
		$edit->pais2->options("SELECT codigo, nombre FROM pais ORDER BY nombre");
		$edit->pais2->group = "Domicilio de Llegada";
		
		$edit->zona2 = new dropdownField("Departamento", "zona2");
        $edit->zona2->db_name='departal';
		$edit->zona2->style = "width:270px";
		//$edit->zona2->rule = "required";
		$edit->zona2->group = "Domicilio de Llegada";
		if($edit->_status=='show'||$edit->_status=='modify'){ 
			$pais =$edit->_dataobject->get("regionl");
			$edit->zona2->options("SELECT codigo, nombre FROM zona WHERE pais='$pais' ORDER BY nombre");
		}else{
			$edit->zona2->option("","Seleccione una Regi&oacute;n");
		}	
    
		$edit->estado2 = new dropdownField("Provincia","estado2");
		//$edit->estado->option("","Seleccione una Zona");
        $edit->estado2->db_name='provincial';
		$edit->estado2->style = "width:270px";
		//$edit->estado2->rule = "required";
		$edit->estado2->group = "Domicilio de Llegada";
		if($edit->_status=='show'||$edit->_status=='modify'){ 
			$zona =$edit->_dataobject->get("departal");
			$edit->estado2->options("SELECT codigo, nombre FROM estado WHERE zona='$zona' ORDER BY nombre");
		}else{
			$edit->estado2->option("","Seleccione un Departamento");
		}	
				
		$edit->municipios2 = new dropdownField("Distrito","municipio2");
		//$edit->municipios->option("","Seleccione un Municipio");
        $edit->municipios2->db_name='distritol';
		$edit->municipios2->style = "width:270px";
		//$edit->municipios2->rule = "required";
		$edit->municipios2->group = "Domicilio de Llegada";
		if($edit->_status=='show'||$edit->_status=='modify'){ 
			$estado   =$edit->_dataobject->get("provincial");
			$zona     =$edit->_dataobject->get("departal");
			$edit->municipios2->options("SELECT codigo, nombre FROM municipio WHERE estado='$estado' and zona='$zona' ORDER BY nombre");
		}else{
			$edit->municipios2->option("","Seleccione una Provincia");
		}
        	
        $edit->destinatario = new inputField("Raz&oacute;n Social", "destinatario");
		$edit->destinatario->size=50;
        $edit->destinatario->rule = "required";
		$edit->destinatario->group = "Destinatario";
        $edit->destinatario->insertValue = $cliente;
        
        $edit->rucd = new inputField("$tipo", "rucd");
		$edit->rucd->size=20;
		$edit->rucd->group = "Destinatario";
        $edit->rucd->insertValue = $rifci;
        
        $edit->tdocu = new inputField("Tipo de Documento de Identidad", "tdocu");
		$edit->tdocu->size=20;
		$edit->tdocu->group = "Destinatario";
        
        $edit->ndocu = new inputField("N&uacute;mero","ndocu");
		$edit->ndocu->size=20;
		$edit->ndocu->group = "Destinatario";
        
        $edit->vehiculo = new inputField("Marca de Vehiculo", "vehiculo");
		$edit->vehiculo->size=20;
        $edit->vehiculo->rule = "strtoupper|required";
		$edit->vehiculo->group = "Unidad de Transporte y Conductor";
        
        $edit->placa = new inputField("Placa", "placa");
		$edit->placa->size=20;
        $edit->placa->rule = "strtoupper|required";
		$edit->placa->group = "Unidad de Transporte y Conductor";
        
        $edit->cinscripcion = new inputField("Certificado de Inscripci&oacute;n", "cinscripcion");
		$edit->cinscripcion->size=20;
		$edit->cinscripcion->group = "Unidad de Transporte y Conductor";
        
        $edit->licencia = new inputField("Licencia del Conductor", "licencia");
		$edit->licencia->size=20;
		$edit->licencia->group = "Unidad de Transporte y Conductor";
        
        $edit->transportista = new inputField("Empresa de Transporte", "transportista");
		$edit->transportista->size=40;
        //$edit->transportista->rule = "required";
		$edit->transportista->group = "Informaci&oacute;n Adicional";
		$edit->transportista->insertValue =$transportista;
		$edit->transportista->append($boton);
        
        $edit->direc = new inputField("Direcci&oacute;n", "direc");
		$edit->direc->size=40;
		$edit->direc->insertValue =$direc;
		$edit->direc->group = "Informaci&oacute;n Adicional";
        
        $edit->atencion = new inputField("Atenci&oacute;n", "atencion");
		$edit->atencion->rule = "strtoupper";
		$edit->atencion->size=40;
		$edit->atencion->insertValue =$atencion;
		$edit->atencion->group = "Informaci&oacute;n Adicional";
		
		$edit->tipod = new inputField("Tipo de Despacho", "tipod");
		$edit->tipod->rule = "strtoupper";
		$edit->tipod->size=40;
		$edit->tipod->insertValue =$tipod;
		$edit->tipod->group = "Informaci&oacute;n Adicional";
        
        $edit->observa = new inputField("Observaci&oacute;n","observa");
        $edit->observa->size=40;
        $edit->observa->rule = "strtoupper";
        $edit->observa->insertValue =$observa;
        $edit->observa->group="Informaci&oacute;n Adicional";
		
		$id   =$edit->_dataobject->get("id");
		$tipo =$edit->_dataobject->get("tipo_doc");
        		        
		IF(($tipo=='FC')OR ($tipo=='')){
			$edit->buttons("back","save","modify"); 
			$accion="javascript:window.location='".site_url("ventas/sfacdespfyco/anular/$id/")."'";
			$edit->button_status('btn_cargar','Anular Gu&iacute;a',$accion,'TR','show');
            $accion_2="javascript:window.location='".site_url("ventas/sfacdespfyco/cancelar/$nguia/")."'";
			$edit->button_status('btn_cargar','Cancelar',$accion_2,'TR','create');

		}ELSE{
			$edit->buttons("back");
			
		}
		

		
		$edit->build();
        
        $data['content'] ='';
        
        if($edit->_status=='show'){ 
            //$nguia=$edit->_dataobject->get("nguia");
            $propiedad = array('src' => 'images/icono_impresora.gif', 'alt' => 'Imprimir', 'title' => 'Imprimir','border'=>'0');		
            $imprime='<a href='.site_url("fsiigo/guia/$nguia").'>'.img($propiedad).'</a>';
             $data['content'] =$imprime;
        }
        
        $nguia   =$edit->_dataobject->get("nguia");
        $data['title'] = heading("Gu&iacute;a de Remisi&oacute;n $nguia");
        $data['script'] = script('jquery.js');
		$data['script'].= script("jquery-ui.js");
		$data['script'].= script("jquery.alerts.js");
		$data['script'].= script('plugins/jquery.numeric.pack.js');
		$data['script'].= script('plugins/jquery.floatnumber.js');
		$data['script'].= script('plugins/jquery.autocomplete.js');
		$data['script'].= script("plugins/jquery.blockUI.js"); 
		$data['script'].= script('nformat.js');
		//$data['script'].= $script;
		$data['head'] = $this->rapyd->get_head();
		$data['content'] .= $edit->output;
		$this->load->view('view_ventanas', $data);	    
        
    }
    function chexiste(){
        
        $nguia=$this->input->post('nguia');
        $nguia =str_pad($nguia, 11, "0", STR_PAD_LEFT);
        
        $chek = $this->datasis->dameval("SELECT factura FROM remision WHERE nguia='$nguia' and tipo_doc='FC'");
        
		if ($chek > 0){
			$this->validation->set_message('chexiste',"N&uacutemero de Gu&iacute;a de Remisi&oacute;n $nguia YA EXISTE para el presupuesto $chek");
			return FALSE;
		}else {
		 return TRUE;
		}
        
    }
    function anular($id){
		
		$mSQL=$this->db->query("SELECT codigo, cantidad, nguia, remision,  factura,  presup
		FROM despachos WHERE remision='$id'");
        
        $nguia=$this->datasis->dameval("SELECT nguia FROM remision WHERE id='$id'");
        $numero=$this->datasis->dameval("SELECT factura FROM remision WHERE id='$id'");
		
		$this->db->query("UPDATE remision  SET tipo_doc='X' WHERE id='$id'");
		$this->db->query("UPDATE despachos SET tipo_doc='X' WHERE remision='$id'");
		
		foreach($mSQL->result() as $items ){
            
            $this->db->query("UPDATE itspre SET cdespacha=cdespacha-'$items->cantidad' WHERE numero='$items->presup' and codigo='$items->codigo'");
        }
				
		$porsiaca=$this->db->query("SELECT codigo,SUM(cantidad)cant FROM despachos WHERE presup='$numero' AND tipo_doc='FC' GROUP BY codigo");
        $result1= $porsiaca->result();
        
        foreach ($result1 AS $items1){
				
            //procedimientos para despachar
            
            $this->db->query("UPDATE itspre SET cdespacha='$items1->cant' WHERE numero='$numero' AND codigo='$items1->codigo'"); 
        }
        
        $this->inventario->sp_costos($id,'3I');
        
		redirect("ventas/sfacdespfyco/dataedit/show/$id");		
	}
    function cancelar($nguia){
		
		$mSQL=$this->db->query("SELECT codigo, cantidad, nguia, remision,  factura,  presup
		FROM despachos WHERE nguia='$nguia'");
		
		foreach($mSQL->result() as $items ){
            
            $this->db->query("UPDATE itspre SET cdespacha=cdespacha-'$items->cantidad' WHERE numero='$items->presup' and codigo='$items->codigo'");
            
        }
		$this->db->query("DELETE FROM despachos WHERE nguia='$nguia'");
		redirect("ventas/sfacdespfyco/");	
	}
    function _pre_delete($do){
		
		
        $id=$do->get('id');
        $nguia=$do->get('nguia');
        
		$mSQL=$this->db->query("SELECT codigo, cantidad, nguia, remision,  factura,  presup
		FROM despachos WHERE remision='$id'");
		
		foreach($mSQL->result() as $items ){
            
            $this->db->query("UPDATE itspre SET cdespacha=cdespacha-'$items->cantidad' WHERE numero='$items->presup' and codigo='$items->codigo'");
            
        }
		
		$this->db->query("DELETE FROM despachos WHERE remision='$id'");
		
		logusu('despachos',"GUIA DE REMISION $nguia ELIMINADA");
	}
	function detalle($numero='',$id_spre=''){
		
			$this->db->query("DELETE FROM despachos WHERE remision IS NULL");
           
            //arreglar despachos
            $mSQL_3=$this->db->query("SELECT codigo FROM itspre WHERE numero='$numero' GROUP BY codigo");
             
            $result= $mSQL_3->result();
			
			foreach ($result AS $items){
							
				//procedimientos para despachar
				$this->db->query("UPDATE itspre SET cdespacha=IF((SELECT SUM(cantidad)cant FROM despachos WHERE presup='$numero' AND codigo='$items->codigo' and tipo_doc='FC' GROUP BY codigo)IS NULL,0,(SELECT SUM(cantidad)cant FROM despachos WHERE presup='$numero' AND codigo='$items->codigo' and tipo_doc='FC'  GROUP BY codigo)) WHERE numero='$numero' AND codigo='$items->codigo'");
			}
            
			
            $this->rapyd->load("datagrid2");
            
            $atts = array(
			 'width'      => '800',
			 'height'     => '600',
			 'scrollbars' => 'yes',
			 'status'     => 'yes',
			 'resizable'  => 'yes',
			 'screenx'    => '0',
			 'screeny'    => '0'
            );
            
            
            //regresa a busqueda
            
            $anchor=anchor('ventas/sfacdespfyco/filteredgrid','Regresar');
            			
            //busca articulos
            
            $mSQL_1 = $this->db->query("SELECT a.numero,a.codigo,a.desca as descrip,a.cana cantidad,a.preca precio,a.importe total,
            a.cdespacha,a.despacha,b.unidad,b.clave,(a.cana-a.cdespacha) a,b.existen
            FROM itspre AS a 
            JOIN sinv AS b ON a.codigo=b.codigo 
            WHERE a.numero='$numero' and b.tipo='01' ORDER BY a DESC");
            
            $mSQL_2 = $this->db->query("SELECT  a.numero
            FROM itspre AS a 
            JOIN sinv AS b ON a.codigo=b.codigo 
            WHERE a.numero='$numero' and b.tipo='01' AND cana>cdespacha");
            
            
			$data2['detalle']= $mSQL_1->result();
			
			$cliente=$this->datasis->dameval("SELECT nombre FROM spre WHERE numero='$numero'");
			            			                      
            //detalle del despacho x articulo
            
            $grid = new DataGrid2('Detalle de los Depachos Realizados');
            $select=array("c.almacen","IF(c.tipo_doc='FC','EMITIDA','ELIMINADA') as tipo",'c.id as remision','a.id as id','descrip','cantidad','a.usuario','a.codigo as codigo','a.nguia','c.fecha','c.ftraslado');
			$grid->db->select($select);
			$grid->db->from('despachos AS a');
            $grid->db->join('sinv as b','a.codigo=b.codigo');
            $grid->db->join('remision as c','a.remision=c.id');
            $grid->db->where('a.presup',$numero);
            $grid->db->where('b.tipo','01');
            $grid->order_by('nguia','asc');
            $grid->agrupar("GU&Iacute;A DE REMISI&Oacute;N ",'nguia');
            $grid->per_page = 10;
            
            $uri2  = anchor("ventas/sfacdespfyco/dataedit/show/<#remision#>",'Ver Guia');
            $uri   = anchor_popup('formatos/ver/GUIA/<#remision#>',img(array('src'=>'images/pdf_logo.gif','border'=>'0','alt'=>'Ver Html','height'=>'15','title'=>'Ver Html')),$atts);
            $uri  .= anchor_popup('formatos/verhtml/GUIA/<#remision#>',img(array('src'=>'images/html_icon.gif','border'=>'0','alt'=>'Ver Html','height'=>'15','title'=>'Ver Html')),$atts);
            //$grid->column("N Guia"                ,$uri                                                     ,"align=left");
            $grid->column("    "                  ,$uri                                                     ,"align=center");
            $grid->column_orderby('Tipo'          ,'tipo'  ,'tipo' ,"align=left");
            $grid->column_orderby('Emision'       ,'<dbdate_to_human><#fecha#></dbdate_to_human>'  ,'fecha' ,"align=center");
            $grid->column_orderby('Traslado'      ,'<dbdate_to_human><#ftraslado#></dbdate_to_human>','ftraslado' ,"align=center");
            $grid->column("ALmacen"               ,"almacen"                                              ,"align=left");
            $grid->column("C&oacute;digo"         ,"codigo"                                                 ,"align=left");
            $grid->column("Descripci&oacute;n"    ,"descrip"                                                ,"align=left");
            $grid->column("Cantidad"              ,"cantidad"                                               ,"align=center");
            $grid->column("Usuario"               ,"usuario"                                                ,"align=center");
             $grid->column("Acci&oacute;n"        ,$uri2                                                     ,"align=center");
           	            
            $grid->output;
            $grid->build();
            
            //Echo $grid->db->last_query(); 
            
            $data2['content'] = $grid->output;
            $data2['numero']  = $numero;
            $data2['id_spre'] = $id_spre;
            $data2['cantmd']=$mSQL_2->num_rows();
            $data['content']  = $this->load->view('view_sfacdesp', $data2,true);
                                
			$data['title']   = heading("Despacho Parcial Presupuesto $numero/$cliente"); 
            $data['filtro']  ="";
            $data['head']    = script("plugins/jquery.checkboxes.pack.js").$this->rapyd->get_head();              
			$this->load->view('view_ventanas', $data);
	}
    function existe($nguia,$numero,$id_spre){
            $uri=anchor("ventas/spre/dataedit/show/$id_spre","$numero");
            $data['content'] = "<span style='color:red'>N&uacutemero de Gu&iacute;a de Remisi&oacute;n $nguia YA EXISTE para el presupuesto </spam> ".$uri;
            $data['filtro']  ="";                  
			$data['title']   = "Gu&iacute;a ya Existe";  
            $data['head']    = script("plugins/jquery.checkboxes.pack.js").$this->rapyd->get_head();              
			$this->load->view('view_ventanas_sola', $data);
    }
	function guardar(){
				
		//se trae los productos
        
        $numero         = $this->input->post('numero');			
		$cdespacha      = $this->input->post('cdespacha');
		$despacha       = $this->input->post('despacha');
		$codigo         = $this->input->post('codigo');
		$usuario        = $this->db->escape($this->session->userdata('usuario'));
		$ultidespachado = $this->input->post('ultidespachado');
		$guia           = $this->input->post('nguia');
		
		$id_spre = $this->datasis->dameval("SELECT id FROM spre WHERE numero='$numero'");
		IF(empty($guia))redirect("ventas/sfacdespfyco/detalle/$numero/$id_spre");
		
		$nguia =str_pad($guia, 11, "0", STR_PAD_LEFT); 
        $chek = $this->datasis->dameval("SELECT factura FROM remision WHERE nguia='$nguia' and tipo_doc='FC'");
        IF($chek>1){
          redirect("ventas/sfacdespfyco/existe/$nguia/$numero/$id_spre");  
        }
								
        //cuenta los productos
        
        $cant = $this->datasis->dameval("SELECT COUNT(*)as cant FROM itspre WHERE numero='$numero' and codigo NOT IN ('FLETE','SEGURO')");
    
		$i=$o=0;
         
		while($o<$cant){
				
			
			$array=array('0'=>$codigo[$i],'1'=>$cdespacha[$i],'2'=>$despacha[$i]);
            
            
            $sql="UPDATE itspre set ultidespachado='$ultidespachado[$i]',udespacha=$usuario,cdespacha=cdespacha+'$ultidespachado[$i]',despacha='$despacha[$i]',fdespacha=CURDATE() WHERE codigo='$codigo[$i]' AND numero='$numero'";
            //echo $sql;
            $mSQL_1 =$this->db->query($sql);
			
             //insertar en tabla despacho
             
            IF($ultidespachado[$i]>0){
				$mSQL_2=$this->db->query("INSERT INTO despachos (idspre,presup, codigo,cantidad,usuario,nguia) VALUES ('$id_spre','$numero','$codigo[$i]','$ultidespachado[$i]',$usuario,'$nguia')"); 
			}
            
            $i++;
			$o++;
		}
            
		redirect("ventas/sfacdespfyco/dataedit/create/$nguia/$numero");
	}
	
    //finaliza despacho 
    
    function cerrar($tipo_doc='',$numero=''){
		
		$data['content'] ='<pre><b style="color:green;">Articulos Despachados</b></pre>';
		
        //link regresar a despacho
        
        $propiedad = array('src' => 'images/regresar.jpg', 'alt' => 'Regresar', 'title' => 'Regresar','border'=>'0','height'=>'80');		
        $back='<a href='.site_url("ventas/sfacdespfyco/detalle/$numero/$tipo_doc").'>'.img($propiedad).'</a>';
        $data['content'] .=$back;
       
        //link imprimir guia
        
        $propiedad = array('src' => 'images/imprime.png', 'alt' => 'Imprimir', 'title' => 'Imprimir','border'=>'0','height'=>'80');		
        $imprime='<a href='.site_url("formatos/ver/SNOTEXP/$tipo_doc/$numero").'>'.img($propiedad).'</a>';
        $data['content'] .=$imprime;
    
        $data['title']   = "<h1>Despacho Parcial</h1>";
		$data["head"]    = script("jquery-1.2.6.pack.js");
		$data["head"]    = script("plugins/jquery.checkboxes.pack.js").$this->rapyd->get_head();
        $data['filtro']  ="";
		$this->load->view('view_ventanas', $data);
		
	}
    //despues de insertar
    function _pre_insert($do){
		
		$fecha=$do->get('fecha');
        
        $cambio=$this->datasis->dameval("SELECT cambio FROM cambio WHERE fecha='$fecha'");
        $do->set('cambio',$cambio);
	
	}
    function _post_insert($do){

		$id=$do->get('id');
        $nguia=$do->get('nguia');
        $numero=$do->get('factura');
        $almacen=$do->get('almacen');
        $fecha=$do->get('fecha');
        
        $cambio=$this->datasis->dameval("SELECT cambio FROM cambio WHERE fecha='$fecha'");
        $do->set('cambio',$cambio);
        
        $this->db->query("UPDATE despachos SET remision='$id',factura=(SELECT fnumero FROM spre AS b WHERE b.numero='$numero') WHERE nguia='$nguia' AND tipo_doc='FC'");
        
		$chek=$this->datasis->dameval("SELECT COUNT(*) FROM despachos WHERE remision='$id'");
		
		IF($chek>0){
		
		
        $this->db->query("DELETE FROM despachos WHERE remision IS NULL AND  presup='$numero'");
        
        $porsiaca=$this->db->query("SELECT codigo,SUM(cantidad)cant FROM despachos WHERE presup='$numero' AND tipo_doc='FC' GROUP BY codigo");
        $result1= $porsiaca->result();
        
        foreach ($result1 AS $items1){
						
            //procedimientos para despachar
            $this->db->query("UPDATE itspre SET cdespacha='$items1->cant' WHERE numero='$numero' AND codigo='$items1->codigo'");             
        }
        
        logusu('despachos',"GUIA DE REMISION $nguia CREADA");
		
		}else{
		
		$this->db->query("DELETE FROM remision WHERE id='$id'");
		echo 'REGISTRE  DE NUEVO';
		return false;
			
		}
		
		$this->inventario->sp_costos($id,'3I');
		
	}
	function _pre_update($do){
		
		$nguia=$do->get('nguia');
		$nguia =str_pad($nguia, 11, "0", STR_PAD_LEFT);
		$do->set('nguia',$nguia);
		
        $fecha=$do->get('fecha');
        
        $cambio=$this->datasis->dameval("SELECT cambio FROM cambio WHERE fecha='$fecha'");
        $do->set('cambio',$cambio);
		
		logusu('despachos',"GUIA DE REMISION $nguia MODIFICADA");
		
	}
	function _post_update($do){
		
		$id=$do->get('id');
		
        $nguia=$do->get('nguia');
		$nguia =str_pad($nguia, 11, "0", STR_PAD_LEFT);
		
		$this->inventario->sp_costos($id,'3I');
		
		$this->db->query("UPDATE despachos SET nguia='$nguia' WHERE remision='$id'");
		
	}
}
?>
